<template>
  <div class="bg-white rounded-lg shadow-sm overflow-hidden">
    <!-- 搜索和筛选区域 -->
    <div class="p-4 border-b border-gray-200">
      <div class="flex flex-wrap items-center gap-4">
        <div class="flex-1 min-w-[200px]">
          <FormItem label="项目名称">
            <Input v-model="searchForm.name" placeholder="请输入项目名称" />
          </FormItem>
        </div>
        <div class="w-full sm:w-auto">
          <FormItem label="项目分类">
            <Select v-model="searchForm.category" placeholder="请选择项目分类">
              <Option v-for="category in itemCategories" :value="category.value" :key="category.value">{{ category.label }}</Option>
            </Select>
          </FormItem>
        </div>
        <div class="w-full sm:w-auto">
          <FormItem label="状态">
            <Select v-model="searchForm.status" placeholder="请选择状态">
              <Option value="">全部</Option>
              <Option value="true">启用</Option>
              <Option value="false">禁用</Option>
            </Select>
          </FormItem>
        </div>
        <div class="w-full sm:w-auto">
          <Button type="primary" @click="searchItems">
            <i class="fa fa-search mr-2"></i>搜索
          </Button>
          <Button @click="resetSearch" class="ml-2">重置</Button>
        </div>
      </div>
    </div>

    <!-- 表格内容区域 -->
    <div class="overflow-x-auto">
      <Table :columns="columns" :data="itemList" border :loading="isLoading">
        <template #category="{ record }">
          {{ getCategoryLabel(record.category) }}
        </template>
        <template #status="{ record }">
          <Switch v-model="record.status" @change="toggleStatus(record)" />
        </template>
        <template #action="{ record }">
          <div class="flex space-x-2">
            <Button type="text" size="small" @click="editItem(record)">
              <i class="fa fa-edit text-blue-500"></i> 编辑
            </Button>
            <Button type="text" size="small" @click="deleteItem(record)">
              <i class="fa fa-trash text-red-500"></i> 删除
            </Button>
          </div>
          </template>
        </Table>
    </div>

    <!-- 分页区域 -->
    <div class="px-4 py-3 flex items-center justify-between border-t border-gray-200">
      <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
        <div>
          <p class="text-sm text-gray-700">
            显示第 <span class="font-medium">{{ (currentPage - 1) * pageSize + 1 }}</span> 至 <span class="font-medium">{{ Math.min(currentPage * pageSize, total) }}</span> 条，共 <span class="font-medium">{{ total }}</span> 条记录
          </p>
        </div>
        <div>
          <Pagination
            @on-change="handlePageChange"
            @on-page-size-change="handleSizeChange"
            :current="currentPage"
            :page-size="pageSize"
            :total="total"
            show-total
            show-sizer
            :page-sizes="[10, 20, 50, 100]"
            simple />
        </div>
      </div>
    </div>
  </div>


</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { Message } from 'view-ui-plus';

// API服务
import { itemApi } from '@/api/physicalExaminationApi/physicalExamination'

// 状态管理
const editModalVisible = ref(false)
const isEditing = ref(false)
const isLoading = ref(false)

// 搜索表单
const searchForm = reactive({
  name: '',
  category: '',
  status: ''
})

// 编辑表单
const editForm = reactive({
  id: '',
  name: '',
  category: '',
  price: 0,
  referenceRange: '',
  unit: '',
  description: '',
  status: true
})

// 表单验证规则
const editRules = reactive({
  name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择项目分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入项目价格', trigger: 'blur' },
    { type: 'number', message: '价格必须为数字', trigger: 'blur' }
  ]
})

// 分页信息
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 静态数据
const itemCategories = [
  { value: 'blood', label: '血液检查' },
  { value: 'urine', label: '尿液检查' },
  { value: 'imaging', label: '影像学检查' },
  { value: 'function', label: '功能检查' },
  { value: 'special', label: '特殊检查' }
]

// 表格列定义
const columns = [
  {
    title: '项目ID',
    key: 'id',
    width: 120
  },
  {
    title: '项目名称',
    key: 'name',
    width: 180
  },
  {
    title: '项目分类',
    key: 'category',
    width: 120
  },
  {
    title: '项目价格(元)',
    key: 'price',
    width: 120
  },
  {
    title: '参考值范围',
    key: 'referenceRange',
    width: 150
  },
  {
    title: '单位',
    key: 'unit',
    width: 80
  },
  {
    title: '状态',
    key: 'status',
    width: 80
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
    align: 'center'
  }
]

// 项目列表数据
const itemList = ref([])

// 生命周期钩子
onMounted(() => {
  fetchItemList()
})

// 获取项目分类标签
const getCategoryLabel = (category: string) => {
  const item = itemCategories.find(c => c.value === category)
  return item?.label || category
}

// 获取项目列表
const fetchItemList = async () => {
  isLoading.value = true
  try {
    const response = await itemApi.getList({
      // ...searchForm,
      // page: currentPage.value,
      // pageSize: pageSize.value
    })
    itemList.value = response.data || []
    // total.value = response.total || 0
  } catch (error) {
    Message.error('获取项目列表失败，请稍后再试')
  } finally {
    isLoading.value = false
  }
}

// 搜索项目
const searchItems = () => {
  currentPage.value = 1
  fetchItemList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.category = ''
  searchForm.status = ''
  searchItems()
}

// 编辑项目
const editItem = (record: any) => {
  isEditing.value = true
  Object.assign(editForm, record)
  editModalVisible.value = true
}

// 删除项目
const deleteItem = async (record: any) => {
  const confirmResult = await Message.confirm(
    '确定要删除此项目吗？此操作不可撤销。',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
  
  if (confirmResult === 'confirm') {
    try {
      await itemApi.delete(record.id)
      Message.success('项目删除成功')
      fetchItemList()
    } catch (error) {
      Message.error('项目删除失败，请稍后再试')
    }
  }
}

// 切换项目状态
const toggleStatus = async (record: any) => {
  try {
    await itemApi.toggleStatus(record.id, record.status)
    Message.success('项目状态更新成功')
  } catch (error) {
    // 回滚状态
    record.status = !record.status
    Message.error('项目状态更新失败，请稍后再试')
  }
}

// 保存项目
const saveItem = async () => {
  // 表单验证
  const isValid = await validateForm()
  if (!isValid) return
  
  try {
    if (isEditing.value) {
      // 更新项目
      await itemApi.update(editForm.id,editForm)
      Message.success('项目更新成功')
    } else {
      // 新增项目
      await itemApi.getList(editForm)
      Message.success('项目添加成功')
    }
    
    fetchItemList()
    hideEditModal()
  } catch (error) {
    Message.error(isEditing.value ? '项目更新失败' : '项目添加失败')
  }
}

// 表单验证
const validateForm = () => {
  return new Promise((resolve) => {
    // 这里应该使用iView的表单验证，示例代码
    resolve(true)
  })
}

// 隐藏编辑模态框
const hideEditModal = () => {
  editModalVisible.value = false
}

// 处理分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchItemList()
}

// 处理每页数量变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchItemList()
}
</script>

<style scoped>
/* 自定义样式 */
</style>    